home *** CD-ROM | disk | FTP | other *** search
/ Linux Cubed Series 7: Sunsite / Linux Cubed Series 7 - Sunsite Vol 1.iso / system / news / inn1.000 / inn1.4sec-linux-src.tar / inn / lib / readin.c < prev    next >
C/C++ Source or Header  |  1992-07-24  |  2KB  |  92 lines

  1. /*  $Revision: 1.4 $
  2. **
  3. */
  4. #include <stdio.h>
  5. #include <errno.h>
  6. #include <sys/types.h>
  7. #include <sys/stat.h>
  8. #include <fcntl.h>
  9. #include "configdata.h"
  10. #include "libinn.h"
  11. #include "clibrary.h"
  12. #include "macros.h"
  13.  
  14.  
  15. /*
  16. **  Read a big amount, looping until it is all done.  Return TRUE if
  17. **  successful.
  18. */
  19. int
  20. xread(fd, p, i)
  21.     register int    fd;
  22.     register char    *p;
  23.     register off_t    i;
  24. {
  25.     register int    count;
  26.  
  27.     for ( ; i; p += count, i -= count)
  28.     if ((count = read(fd, p, (SIZE_T)i)) <= 0)
  29.         return -1;
  30.     return 0;
  31. }
  32.  
  33.  
  34. /*
  35. **  Read an already-open file into memory.
  36. */
  37. char *
  38. ReadInDescriptor(fd, Sbp)
  39.     int        fd;
  40.     struct stat    *Sbp;
  41. {
  42.     struct stat    mystat;
  43.     char    *p;
  44.     int        oerrno;
  45.  
  46.     if (Sbp == NULL)
  47.     Sbp = &mystat;
  48.  
  49.     /* Get the size, and enough memory. */
  50.     if (fstat(fd, Sbp) < 0) {
  51.     oerrno = errno;
  52.     (void)close(fd);
  53.     errno = oerrno;
  54.     return NULL;
  55.     }
  56.     p = NEW(char, Sbp->st_size + 1);
  57.  
  58.     /* Slurp, slurp. */
  59.     if (xread(fd, p, Sbp->st_size) < 0) {
  60.     oerrno = errno;
  61.     DISPOSE(p);
  62.     (void)close(fd);
  63.     errno = oerrno;
  64.     return NULL;
  65.     }
  66.  
  67.     /* Terminate the string; terminate the routine. */
  68.     p[Sbp->st_size] = '\0';
  69.     return p;
  70. }
  71.  
  72.  
  73. /*
  74. **  Read a file into allocated memory.  Optionally fill in the stat(2) data.
  75. **  Return a pointer to the file contents, or NULL on error.
  76. */
  77. char *
  78. ReadInFile(name, Sbp)
  79.     char    *name;
  80.     struct stat    *Sbp;
  81. {
  82.     char    *p;
  83.     int        fd;
  84.  
  85.     if ((fd = open(name, O_RDONLY)) < 0)
  86.     return NULL;
  87.  
  88.     p = ReadInDescriptor(fd, Sbp);
  89.     (void)close(fd);
  90.     return p;
  91. }
  92.